package cn.tedu.csmall.resource.controller;


import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.web.JsonResult;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.resource.pojo.vo.UploadResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 处理文件上传的控制器类
 */


@Slf4j
@RestController
@RequestMapping("/resources")
@Api(tags = "文件上传模块")
public class ResourceController {

    @Value("${csmall.upload.host}")
    private String host;
    @Value("${csmall.upload.base-dir}")
    private String baseDir;
    @Value("${csmall.upload.product-image.types}")
    private List<String> productImageTypes;
    @Value("${csmall.upload.product-image.max-size}")
    private Integer productImageMaxSize;
    @Value("${csmall.upload.product-image.dir}")
    private String productImageDir;

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload/image/product")
    @ApiOperation("上传商品图片")
    public JsonResult uploadProductImage(
            @RequestParam("imageFile") MultipartFile file) throws Throwable{
        if(file == null || file.isEmpty()){
            String message = "上传商品图片失败，请选择您要上传的文件！";
            throw new ServiceException(ServiceCode.ERR_UPLOAD_EMPTY, message);
        }

        long size = file.getSize();
        if(size > productImageMaxSize * 1024 * 1024){
            String message = "上传商品图片失败，不允许使用超过" + productImageMaxSize + "MB的图片文件！";
            throw new ServiceException(ServiceCode.ERR_UPLOAD_EXCEED_MAX_SIZE, message);
        }

        String contentType = file.getContentType();
        if(!productImageTypes.contains(contentType)){
            String message = "上传商品图片失败，请使用以下类型的图片文件：" + productImageTypes;
            throw new ServiceException(ServiceCode.ERR_UPLOAD_INVALID_TYPE, message);
        }
        //日期目录
        String dirName = sdf.format(new Date());
        File productUploadDir = new File(baseDir+productImageDir, dirName);
        if(!productUploadDir.exists()){
            productUploadDir.mkdirs();
        }

        //文件名转换
        String originalFilename = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFullFileName = newFileName+suffix;
        File newFile = new File(productUploadDir, newFullFileName);
        file.transferTo(newFile);

        String url = new StringBuilder()
                .append(host).append(productImageDir)
                .append(dirName).append(newFullFileName).toString();

        UploadResult uploadResult = new UploadResult();
        uploadResult.setUrl(url).setFileName(newFullFileName)
                .setContentType(contentType).setFileSize(size);

        return JsonResult.ok(uploadResult);
    }

    @PostMapping("/remove/image/product")
    @ApiOperation("删除图片")
    public JsonResult remove(String url){
        int index = url.indexOf(productImageDir);
        String newUrl = baseDir + url.substring(index);
        new File(newUrl).delete();
        return JsonResult.ok();
    }
}
